#!/usr/bin/env bash
# OctoPI generation script
# Helper script that runs in a Raspbian chroot to create the OctoPI distro
# Written by Guy Sheffer <guysoft at gmail dot com> and Gina Häußge <osd@foosel.net>
# GPL V3
########
set -x
set -e

export LC_ALL=C

source /common.sh

### Script ####

unpack /filesystem/home/pi /home/pi pi
unpack /filesystem/home/root /root root
unpack /filesystem/boot /boot
apt-get update

# in case we are building from a regular raspbian image instead of the lite one...
remove_extra=$(remove_if_installed scratch squeak-plugins-scratch squeak-vm wolfram-engine python-minecraftpi minecraft-pi sonic-pi oracle-java8-jdk bluej libreoffice-common libreoffice-core freepats greenfoot nodered)
echo "removing:" $remove_extra
apt-get remove -y --purge  $remove_extra
apt-get autoremove -y

apt-get -y --force-yes install python2.7 python-virtualenv python-dev git screen subversion cmake checkinstall avahi-daemon libavahi-compat-libdnssd1 libffi-dev libssl-dev

echo " - Reinstall iputils-ping"
apt-get install --reinstall iputils-ping


pushd /home/pi

  #build virtualenv
  sudo -u pi virtualenv oprint
  
  sudo -u pi /home/pi/oprint/bin/pip install --upgrade pip

  # OctoPrint & pyserial
  if [ "$OCTOPI_INCLUDE_OCTOPRINT" == "yes" ]
  then
    echo "--- Installing OctoPrint"

    #pybonjour (for mdns discovery)
    sudo -u pi /home/pi/oprint/bin/pip install $OCTOPI_PYBONJOUR_ARCHIVE

    #OctoPrint
    PIP_DEFAULT_TIMEOUT=60 sudo -u pi /home/pi/oprint/bin/pip install $OCTOPI_OCTOPRINT_ARCHIVE
  fi

  #mjpg-streamer
  if [ "$OCTOPI_INCLUDE_MJPGSTREAMER" == "yes" ]
  then
    echo "--- Installing mjpg-streamer"
    if [ $( is_in_apt libjpeg62-turbo-dev ) -eq 1 ]; then
      apt-get -y --force-yes install libjpeg62-turbo-dev
    elif [ $( is_in_apt libjpeg8-dev ) -eq 1 ]; then 
      apt-get -y --force-yes install libjpeg8-dev
    fi
    
    apt-get -y --force-yes --no-install-recommends install imagemagick ffmpeg libv4l-dev
    gitclone OCTOPI_MJPGSTREAMER_REPO mjpg-streamer
    pushd mjpg-streamer
      mv mjpg-streamer-experimental/* .
      sudo -u pi make

      # create our custom web folder and add a minimal index.html to it
      sudo -u pi mkdir www-octopi
      pushd www-octopi
        cat <<EOT >> index.html
<html>
<head><title>mjpg_streamer test page</title></head>
<body>
<h1>Snapshot</h1>
<p>Refresh the page to refresh the snapshot</p>
<img src="./?action=snapshot" alt="Snapshot">
<h1>Stream</h1>
<img src="./?action=stream" alt="Stream">
</body>
</html>
EOT
      popd
    popd
  fi
  
  #CuraEngine
  if [ "$OCTOPI_INCLUDE_CURAENGINE" == "yes" ]
  then
    echo "--- Installing CuraEngine"
    folder=CuraEngine-$OCTOPI_CURAENGINE_VERSION
    zipfile=$folder.zip
    apt-get -y install gcc-4.9 g++-4.9
    sudo -u pi wget -O$zipfile $OCTOPI_CURAENGINE_ARCHIVE
    sudo -u pi unzip $zipfile
    pushd $folder
      sudo -u pi make CXX=g++-4.9 VERSION=$OCTOPI_CURAENGINE_VERSION
      cp build/CuraEngine /usr/local/bin/cura_engine
    popd
    sudo -u pi rm -r $folder $zipfile
  fi

  #setup haproxy for http and https, and webcam
  if [ "$OCTOPI_INCLUDE_HAPROXY" == "yes" ]
  then
    echo "--- Installing haproxy"
    apt-get -y --force-yes install ssl-cert haproxy
    rm /etc/ssl/private/ssl-cert-snakeoil.key /etc/ssl/certs/ssl-cert-snakeoil.pem
  fi

  if [ "$OCTOPI_INCLUDE_WIRINGPI" == "yes" ]
  then
    echo "--- Installing WiringPi"
    apt-get install wiringpi
  fi

  # fetch current yq build and install to /usr/local/bin
  wget -O yq $OCTOPI_YQ_DOWNLOAD && chmod +x yq && mv yq /usr/local/bin
  
popd

#Make sure user pi has access to serial ports
usermod -a -G tty pi
usermod -a -G dialout pi

# store octopi commit used to build this image
echo "$OCTOPI_COMMIT" > /etc/octopi_commit

# Keep legacy compatibility
ln -s /etc/custompios_buildbase /etc/octopi_buildbase

# allow pi user to run shutdown and service commands
echo "pi ALL=NOPASSWD: /sbin/shutdown" > /etc/sudoers.d/octoprint-shutdown
echo "pi ALL=NOPASSWD: /usr/sbin/service" > /etc/sudoers.d/octoprint-service

#make sure users don't run git with sudo, thus breaking permissions, by adding /root/bin to the
#default sudo path and placing a git wrapper script there that checks if it's run as root
sed -i "s@secure_path=\"@secure_path=\"/root/bin:@g" /etc/sudoers
chmod +x /root/bin/git

# add some "How To" info to boot output
# Note, this code is also in /filesystem/home/pi/scripts/
sed -i 's@exit 0@@' /etc/rc.local
cat <<'EOT' >> /etc/rc.local

echo
echo "------------------------------------------------------------"
echo
echo "You may now open a web browser on your local network and "
echo "navigate to any of the following addresses to access "
echo "OctoPrint:"
echo
for name in $_NAME;
do
    echo " http://$name.local"
done

for ip in $(hostname -I);
do 
    echo "    http://$ip"
done

echo
echo "https is also available, with a self-signed certificate."
echo 
echo "------------------------------------------------------------"
echo
EOT

echo 'exit 0' >> /etc/rc.local

# add a longer welcome text to ~pi/.bashrc
echo "source /home/pi/scripts/welcome" >> /home/pi/.bashrc

#unpack root in the end, so etc file are not overwritten, might need to add two roots int he future
unpack /filesystem/root /

#####################################################################
### setup services

### Disable GUI at start
systemctl_if_exists disable lightdm.service || true

update-rc.d change_password defaults
update-rc.d change_hostname defaults


### OctoPrint

if [ "$OCTOPI_INCLUDE_OCTOPRINT" == "yes" ]
then
  update-rc.d octoprint defaults 95
else
  # let's remove the configs for system services we don't need
  rm /etc/init.d/octoprint
  rm /etc/default/octoprint
fi

### haproxy

if [ "$OCTOPI_INCLUDE_HAPROXY" == "yes" ]
then
  systemctl_if_exists enable gencert.service
else
  # let's remove the configs for system services we don't need
  rm /etc/systemd/system/gencert.service

  # also we need to make OctoPrint bind to all interfaces because otherwise
  # it will be unaccessible...
  [ -f /etc/default/octoprint ] && sed -i "s@HOST=127.0.0.1@HOST=0.0.0.0@" /etc/default/octoprint 
fi

### CuraEngine

if [ ! "$OCTOPI_INCLUDE_CURAENGINE" == "yes" ]
then
  # unconfigure the cura engine path in octoprint's config.yaml
  sudo -u pi sed -i -e "s@cura_engine: /usr/local/bin/cura_engine@cura_engine:@g" /home/pi/.octoprint/config.yaml
fi

### mjpg_streamer

if [ "$OCTOPI_INCLUDE_MJPGSTREAMER" == "yes" ]
then
  systemctl_if_exists enable webcamd.service
else
  rm /etc/logrotate.d/webcamd
  rm /etc/init.d/webcamd
  rm /etc/default/webcamd
  rm /root/bin/webcamd
fi

#cleanup
apt-get clean
apt-get autoremove -y

